package io.xuan.modules.app.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class AsyncServer {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

//    @Async
//    public void processOrder(String orderId) {
//        // 模拟订单处理时间
//        try {
//            Thread.sleep(2000);
//            System.out.println("Order " + orderId + " processed");
//        } catch (InterruptedException e) {
//            Thread.currentThread().interrupt();
//        }
//    }


    //@Scheduled(fixedDelay = 5000)
    public void orderWorker() {
        while (true) {
            Long queueSize = redisTemplate.opsForList().size("order_queue");
            if (queueSize != null && queueSize == 0) {
                //System.out.println("Queue is empty. Exiting the loop.");
                break;
            }

            System.out.println("inhere");
            String orderId = redisTemplate.opsForList().rightPop("order_queue");
            if (orderId != null) {
                // 尝试获取分布式锁
                String lockKey = "order_lock:" + orderId;
                Boolean lock = redisTemplate.opsForValue().setIfAbsent(lockKey, "locked");
                if (lock != null && lock) {
                    //asyncServer.processOrder(orderId);

                    // 释放分布式锁
                    redisTemplate.delete(lockKey);
                }
            }
        }
    }

    // 订单处理线程
    // 每隔5秒执行一次
//    @Scheduled(fixedRate = 5000)
}
